<!doctype html>
<html lang="en">
  <head>
    <script src="https://unpkg.com/axios@0.24.0/dist/axios.min.js"></script>
  </head>
  <body>
    <input id="fileInput" type="file" />

    <input id="filesInput" type="file" multiple />

    <input id="filesNamesInput" type="file" multiple />
    <script>
      const fileInput = document.querySelector('#fileInput');
      const filesInput = document.querySelector('#filesInput');
      const filesNamesInput = document.querySelector('#filesNamesInput');
      // 单个文件
      async function singleFile() {
        const data = new FormData();
        data.set('name', '光');
        data.set('age', 20);
        data.set('singleFile', fileInput.files[0]);

        const res = await axios.post('/api/person/singleFile', data, {
          headers: { 'content-type': 'multipart/form-data' },
        });
        console.log(res);
      }
      // 多个文件
      async function multiFile() {
        const data = new FormData();
        data.set('name', '光');
        data.set('age', 20);
        [...filesInput.files].forEach((item) => {
          data.append('multiFile', item);
        });

        const res = await axios.post('/api/person/multiFile', data, {
          headers: { 'content-type': 'multipart/form-data' },
        });
        console.log(res);
      }
      // 多个文件名
      async function namesFiles() {
        const data = new FormData();
        data.set('name', '光');
        data.set('age', 20);
        data.append('m1', filesNamesInput.files[0]);
        data.append('m2', filesNamesInput.files[1]);

        const res = await axios.post('/api/person/namesFiles', data, {
          headers: { 'content-type': 'multipart/form-data' },
        });
        console.log(res);
      }

      fileInput.onchange = singleFile; // 单文件上传
      filesInput.onchange = multiFile; // 多文件上传
      filesNamesInput.onchange = namesFiles; // 多个文件名上传
    </script>
  </body>
</html>
